package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"perm-master/cache"
	"perm-master/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	types := c.PostForm("types")
	img := c.PostForm("img")
	if title == "" || content == "" || types == "" || img == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}

	data := models.Prod{

		Title:   title,
		Content: content,
		Types:   types,
		Img:     img,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	redis_per := "redis_add_" + strconv.Itoa(int(data.ID))
	var perm models.Prod
	models.DB.Where("id=?", data.ID).First(&perm)
	jsonData, _ := json.Marshal(data)
	cache.Rdb.Set(cache.Ctx, redis_per, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var arr models.Prod
	redis_trl := "redis_detail_" + id
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_trl).Result()
	if redisData == "" {
		models.DB.Where("id=?", id).Find(&arr)
		jsondata, _ := json.Marshal(arr)
		cache.Rdb.Set(cache.Ctx, redis_trl, jsondata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &arr)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "详情成功",
		"list": arr,
	})
}
func Del(c *gin.Context) {
	id := c.Query("id")
	var arr models.Prod
	redis_key := "redis_del" + id
	models.DB.Where("id=?", id).Delete(&arr)
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})

}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "3"))
	offset := (page - 1) * pageSize
	var arr []models.Prod
	redis_key := "redis_list" + strconv.Itoa(page)
	redis_data, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redis_data == "" {
		models.DB.Offset(offset).Limit(pageSize).Find(&arr)
		jsonData, _ := json.Marshal(arr)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redis_data), &arr)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": arr,
	})

}
